package com.xxxx.springboot.shiro.config;

import java.util.List;
import java.util.stream.Collectors;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxxx.db.entity.RolesPermissions;
import com.xxxx.db.entity.UserRoles;
import com.xxxx.db.entity.Users;
import com.xxxx.db.service.IRolesPermissionsService;
import com.xxxx.db.service.IUserRolesService;
import com.xxxx.db.service.IUsersService;

public class CustomRealm extends AuthorizingRealm {
	@Autowired
	private IUsersService usersService;

	@Autowired
	private IUserRolesService userRolesService;

	@Autowired
	private IRolesPermissionsService rolesPermissionsService;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		String username = (String) SecurityUtils.getSubject().getPrincipal();
		List<UserRoles> userRoles = userRolesService
				.list(new LambdaQueryWrapper<UserRoles>().eq(UserRoles::getUsername, username));

		List<RolesPermissions> rolesPermissions = rolesPermissionsService
				.list(new LambdaQueryWrapper<RolesPermissions>().in(RolesPermissions::getRoleName,
						userRoles.stream().map(a -> a.getRoleName()).collect(Collectors.toSet())));
		// 数据库查询权限
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(rolesPermissions.stream().map(a -> a.getPermission()).collect(Collectors.toSet()));
		// 对前端采取统一返回，无权限
		return info;
	}

	/**
	 * 这里可以注入userService,为了方便演示，我就写死了帐号了密码 private UserService userService;
	 * <p>
	 * 获取即将需要认证的信息
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		System.out.println("-------身份认证方法--------");
		String userName = (String) authenticationToken.getPrincipal();
		// TODO 改为密文传递
		String userPwd = new String((char[]) authenticationToken.getCredentials());
		System.out.println("-------用户名：" + userName + "    密码：" + userPwd);
		Users user = usersService
				.getOne(new LambdaQueryWrapper<Users>().eq(Users::getUsername, userName).last("limit 1"));

		if (user == null) {
			// 区分错误类型，后期对错误进行处理跳转不同页面
			throw new AccountException("用户名或密码不正确");
		}
		// 根据用户名从数据库获取密码
		String password = user.getPassword();

		// 你注册的加密方式和设置的加密方式还有Realm中身份认证的方式都是要一模一样的。本文中的加密 ：MD5两次、salt=username+salt加密。
		return new SimpleAuthenticationInfo(userName, password, ByteSource.Util.bytes(userName + "salt"), getName());
	}

}
